﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.Dictionary
{
    /// <summary>
    /// Dictionary 的摘要说明
    /// </summary>
    public class Dictionary : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "Dictionary": LoadDictionaryList(); break; //字典列表
            }
        }

        /// <summary>
        /// 字典列表
        /// </summary>
        private void LoadDictionaryList()
        {
            StringBuilder sqlWhere = new StringBuilder();
            string DictionaryName = con.Request["DictionaryName"].ToString2();

            if (!string.IsNullOrEmpty(DictionaryName))
            {
                sqlWhere.Append($" and DictionaryName like '%{DictionaryName}%'");
            }
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT * FROM dbo.SYS_Dictionary
            WHERE IsDelete=0 {sqlWhere}
            ORDER BY Sort ASC"));

            string strJson = JsonConvert.SerializeObject(dt);
            con.Response.Write(strJson);
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Dictionary": GetDictionary(); break; //获取字典
            }
        }

        /// <summary>
        /// 获取字典
        /// </summary>
        private void GetDictionary()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("SYS_Dictionary", "GUID", guid);

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Dictionary": SetDictionary(); break; //字典保存
            }
        }

        /// <summary>
        /// 字典保存
        /// </summary>
        private void SetDictionary()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();
                string parentGUID = con.Request["ParentGUID"].ToString2();
                string dictionaryCode = con.Request["DictionaryCode"].ToString2();

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT GUID FROM dbo.SYS_Dictionary WHERE IsDelete=0 AND DictionaryCode='{dictionaryCode}' AND GUID!='{guid}'"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    json.msg = "字典编码已存在！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                Hashtable ht = systemidao.AddHashtable("SYS_Dictionary", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                bool result = systemidao.SubmitData("SYS_Dictionary", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "Dictionary": DelDictionary(); break; //字典删除
            }
        }

        /// <summary>
        /// 字典删除
        /// </summary>
        private void DelDictionary()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("SYS_Dictionary", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}